import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import { View } from '@tarojs/components'

import { AtTextarea, AtToast, AtButton }  from 'taro-ui'

import { add } from '../../actions/feedbacks'

import './Feedbacks.scss'

type PageStateProps = {
  feedbacks: object | {},
}

type PageDispatchProps = {
  add: (data:object, callback: object) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface FeedBacks {
  props: IProps
}

@connect(({ feedbacks }) => ({
  feedbacks
}), (dispatch) => ({
  add(data, callback) {
    dispatch(add(data, callback))
  }
}))
class FeedBacks extends Component {
    config: Config = {
      navigationBarTitleText: '意见反馈'
    }

    state = {
      data:{
         content: ''
      },
      disabled: false,
      isToastOpened: false,
      toastTips: '内容不能为空！'
    }

    componentDidMount() {
        
    }

    handleTextareaChange = e => {
      this.setState(state => ({
          ...state,
          data: {
            ...state.data,
            content: e.target.value
          }
      }))
    }

    handleSubmit = () => {
        if(String(this.state.data.content).trim() === '') {
          this.setState(state => ({
            ...state,
            isToastOpened: true,
          }))
        } else {
          this.props.add(this.state.data, data => {
            if(data.errno) {
              this.setState(state => ({
                ...state,
                isToastOpened: true,
                toastTips: '意见反馈提交失败!'
              }))
            } else {
              this.setState(state => ({
                ...state,
                disabled: true,
                isToastOpened: true,
                toastTips: '意见反馈提交成功~'
              }))
            }
            console.log(data, 'callback')
          })
        }
    }

    render() {
        return (
            <View className='feedback'>
              <AtToast isOpened={this.state.isToastOpened} text={this.state.toastTips} />
              <AtTextarea
                value={this.state.data.content}
                onChange={this.handleTextareaChange}
                maxlength='200'
                placeholder='请输入您对我们的意见或建议'
              />
              <View className='buttonFix'>
                <AtButton className='btn' type='primary' onClick={this.handleSubmit} disabled={this.state.disabled}>提交</AtButton>
              </View>
            </View>
        )
    }
}

export default FeedBacks as ComponentClass<PageOwnProps, PageState>